package uestc.lj.basic.sort;

import java.util.Arrays;

/**
 * 选择排序
 *
 * @Author:Crazlee
 * @Date:2021/11/20
 */
public class Code01_SelectionSort {
    public static void selectionSort(int[] array) {
        if (array == null || array.length < 2) {
            return;
        }
        for (int i = 0; i < array.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < array[minIndex]) {
                    minIndex = j;
                }
            }
            swap(array, i, minIndex);
        }
    }

    public static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    public static void main(String[] args) {
        int[] array = {5, 7, 8, 2, 6, 1, 9, 3, 4};
        System.out.println("选择排序之前数组元素为：");
        Arrays.stream(array).forEach(value -> System.out.print(value + " "));
        selectionSort(array);
        System.out.println();
        System.out.println("选择排序之后数组的元素为：");
        Arrays.stream(array).forEach(value -> System.out.print(value + " "));
    }
}
